from django.shortcuts import render

# Create your views here.
from rest_framework.generics import ListAPIView,RetrieveAPIView
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from . import serializers
from .models import Area

# class AreasView(ListAPIView):
#     """省份列表"""
#     serializer_class = serializers.AreasSerializer
#     queryset = Area.objects.filter(parent=None)
#
# class AreaView(RetrieveAPIView):
#     """获取当前行政区划信息以及子行政区划信息"""
#     serializer_class = serializers.AreaSerializer
#     queryset = Area.objects.all()


# 设置缓存类，必须放在最左边
class AreasViewSet(CacheResponseMixin, ReadOnlyModelViewSet):
    # 在当前视图类中关闭列表分页功能
    pagination_class = None

    # 根据判断选择不同的序列化器类
    def get_serializer_class(self):
        if self.action == 'list':
            """如果url中没有附带pk，则当前的请求为list"""
            return serializers.AreasSerializer
        else:
            return serializers.AreaSerializer

    # 根据判断选择不同的查询集
    def get_queryset(self):
        if self.action == "list":
            return Area.objects.filter(parent=None)
        else:
            return Area.objects.all()